<template>
  <div style="display: flex">
    <div id="qcLineChart" style="width:70%;height: 300px;"></div>
    <div id="qcPieChart" style="width:30%;height: 300px;"></div>
  </div>
</template>
<script>
export default {
  props: {
    title: String,
    xData: Array,
    yData: Array
  },
  data() {
    return {
      lineChart: null,
      pieChart: null
    }
  },
  watch: {
    title: function(newVal,oldVal){
      //当值动态变化时，刷新图表
      this.initChart();
    },
    xData: function(newVal,oldVal){
      //当值动态变化时，刷新图表
      this.initChart();
    },
    yData: function(newVal,oldVal){
      //当值动态变化时，刷新图表
      this.initChart();
    }
  },
  beforeDestroy() {
    if (!this.lineChart && !this.pieChart ) {
      return
    }
    this.lineChart.dispose();
    this.pieChart.dispose();
    this.lineChart = null;
    this.pieChart = null;
  },
  methods: {
    initChart() {
      this.lineChart = this.$echarts.init(document.getElementById('qcLineChart'));
      // 绘制图表
      this.lineChart.setOption({
        title: {
          text: '趋势分析',
          x: 'left'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: [this.title]
        },
        toolbox: {
          show: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.xData
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [
          {
            name: this.title,
            type: 'line',
            data: this.yData
          }
        ]
      });

      this.pieChart = this.$echarts.init(document.getElementById('qcPieChart'));
      this.pieChart.setOption({
        title: {
          text: '对比图',
          // subtext: 'Fake Data',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            type: 'pie',
            radius: '50%',
            data: this.lineToPie(),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
    },
    lineToPie(){
      let pieData = [];
      for(let i = 0; i < this.xData.length; i++){
        pieData.push({
          name: this.xData[i],
          value: this.yData[i]
        })
      }

      return pieData;
    }
  }
}
</script>
